<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.sysAccessKeyId ? $t('brand.add') : $t('user.editBtn')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') === 'language' ? '150px' : '120px'"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('sys.keyName')"
        prop="name"
      >
        <el-input
          v-model="dataForm.name"
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.sysType')"
        maxlength="30"
        prop="type"
      >
        <el-radio-group
          v-model="dataForm.sysType"
          @change="updateSysType(dataForm.sysType)"
        >
          <el-radio
            v-for="(type, index) in dataForm.typeList"
            :key="index"
            :label="index"
          >
            {{ type }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="dataForm.sysType === 1"
        :label="$t('shop.businessScope')"
        prop="type"
      >
        <el-radio-group v-model="dataForm.shopRange">
          <el-radio :label="1">
            {{ $t('shop.AllMerchants') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('shop.designatedMerchant') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="dataForm.sysType === 1 && dataForm.shopRange === 2">
        <select-account-range
          v-if="!dataForm.usabilityShopId"
          :table-list="dataForm.shopDetailList"
          :type="1"
          :shop-id="dataForm.usabilityShopId"
          :single-election="1"
          @get-ids="(id) => dataForm.usabilityShopId = id"
        />
        <el-form-item
          v-else-if="showInfo?.shopName"
          :label="$t('shop.storeName')"
        >
          {{ showInfo.shopName }}&nbsp;
          <el-icon @click.stop="dataForm.usabilityShopId = 0">
            <Close />
          </el-icon>
        </el-form-item>
      </template>
      <el-form-item
        :label="$t('crud.remark')"
        prop="remark"
      >
        <el-input
          v-model="dataForm.remark"
          type="textarea"
          maxlength="100"
          :autosize="{ minRows: 3, maxRows: 6}"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.sysAccessKeyId"
        :label="$t('sys.accessId')"
        prop="remark"
      >
        <span> {{ dataForm.accessId }} </span>
      </el-form-item>
      <el-form-item
        v-if="dataForm.sysAccessKeyId"
        :label="$t('sys.key')"
        prop="remark"
      >
        <span> {{ dataForm.accessKey }} </span>
      </el-form-item>
      <el-form-item
        v-if="dataForm.sysType !== 0"
        :label="$t('sys.authorize')"
      >
        <div>
          <div>
            <el-radio-group v-model="dataForm.premType">
              <el-radio :label="0">
                {{ $t('sys.fullAccess') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('sys.specifyPermissions') }}
              </el-radio>
            </el-radio-group>
          </div>
          <template v-if="dataForm.premType===1">
            <el-tree
              v-if="dataForm.sysType===1"
              ref="menuListTreeRef"
              :data="treeDataShopMenuList"
              style="flex:1"
              :props="menuListTreeProps"
              node-key="menuId"
              show-checkbox
            />
            <el-tree
              v-else
              ref="menuListTreeRef"
              :data="treeDateSysMenuList"
              style="flex:1"
              :props="menuListTreeProps"
              node-key="menuId"
              show-checkbox
            />
          </template>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('coupon.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit(dataFormRef)"
        >
          {{ $t('coupon.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { isHtmlNull } from '@/utils/index.js'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const dataFormRef = ref(null)
const dataForm = reactive({
  sysAccessKeyId: 0,
  sysType: 0,
  usabilityShopId: 0,
  name: null,
  menuIdList: [],
  remark: null,
  accessId: null,
  accessKey: null,
  typeList: [$t('sys.ordinary'), $t('sys.multishop'), $t('sys.platform')],
  access_id: null
})
const menuListTreeRef = ref(null)
const menuList = ref([])
const sysMenuList = ref([])
const shopMenuList = ref([])
const actualMenuList = ref([])
const menuListTreeProps = reactive({
  label: 'name',
  children: 'children'
})
const isSubmit = ref(false)
const dataRule = {
  name: [
    { required: true, message: $t('sys.NameNoNull'), trigger: 'blur' }
  ]
}

const init = (id, sysType) => {
  dataForm.sysAccessKeyId = id || 0
  dataForm.sysType = sysType || 0
  visible.value = true
  isSubmit.value = false
  showInfo.value = null
  dataForm.usabilityShopId = 0
  let nodeList = []
  nextTick(() => {
    dataFormRef.value?.resetFields()
    http({
      url: http.adornUrl('/sys/menu/table'),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      sysMenuList.value = data
      if (dataForm.sysType === 2) {
        menuList.value = treeDataTranslate(data, 'menuId', 'parentId')
      }
      if (dataForm.sysAccessKeyId) {
        nodeList = getNode(menuList.value)
      }
    }).then(() => {
      http({
        url: http.adornUrl('/sys/shopMenu/table'),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        shopMenuList.value = data
        if (dataForm.sysType === 1) {
          menuList.value = treeDataTranslate(data, 'menuId', 'parentId')
        }
        if (dataForm.sysAccessKeyId) {
          nodeList = getNode(menuList.value)
        }
      })
    }).then(() => {
      if (dataForm.sysAccessKeyId) {
        http({
          url: http.adornUrl('/platform/sysAccessKey/info/' + dataForm.sysAccessKeyId),
          method: 'get',
          params: http.adornParams()
        }).then(({ data }) => {
          dataForm.sysAccessKeyId = data.sysAccessKeyId
          dataForm.name = data.name
          dataForm.remark = data.remark
          dataForm.accessId = data.accessId
          dataForm.accessKey = data.accessKey
          dataForm.usabilityShopId = data.usabilityShopId
          dataForm.sysType = data.sysType
          dataForm.shopRange = data.usabilityShopId !== 0 ? 2 : 1
          const selectMenuIdList = data.menuIdList.filter(x => !nodeList.includes(x))
          menuListTreeRef.value?.setCheckedKeys(selectMenuIdList)
        })
      }
    })
  })
}

// 查找菜单节点id
const getNode = (list) => {
  const res = []
  list.forEach(item => {
    if (item.children) {
      res.push(item.menuId, ...getNode(item.children))
    }
  })
  return res
}
const getNodeComputed = computed(() => {
  const list = menuList.value || []
  const res = []
  list.forEach(item => {
    if (item.children) {
      res.push(item.menuId, ...getNode(item.children))
    }
  })
  return res
})
const treeDateSysMenuList = computed(() => {
  return treeDataTranslate(sysMenuList.value, 'menuId', 'parentId')
})
const treeDataShopMenuList = computed(() => {
  return treeDataTranslate(shopMenuList.value, 'menuId', 'parentId')
})

watch(() => dataForm.usabilityShopId, (val) => {
  if (val) {
    getshopInfo(val)
  }
})
watch(() => [dataForm.sysType, dataForm.shopRange], ([sysType, shopRange]) => {
  if (sysType !== 1 || shopRange !== 2) {
    dataForm.usabilityShopId = 0
  }
})

const showInfo = ref(null)
const getshopInfo = (shopId) => {
  http({
    url: http.adornUrl('/shop/shopAuditing/shopDetail/' + shopId),
    method: 'get'
  }).then(({ data }) => {
    showInfo.value = data
  })
}
// 查找菜单节点id
const updateSysType = (sysType) => {
  dataForm.menuIdList = []
  let nodeList = []
  if (sysType === 1) {
    menuList.value = treeDataShopMenuList.value
  } else {
    menuList.value = treeDateSysMenuList.value
  }
  if (dataForm.sysAccessKeyId) {
    nodeList = getNodeComputed.value
  }
  const selectMenuIdList = dataForm.menuIdList.filter(x => !nodeList.includes(x))
  menuListTreeRef.value?.setCheckedKeys(selectMenuIdList)
}

// 表单提交
const onSubmit = () => {
  const menuIdList = [].concat(menuListTreeRef.value?.getCheckedKeys(), menuListTreeRef.value?.getHalfCheckedKeys())
  if (!menuIdList.length && dataForm.sysType !== 0 && dataForm.premType === 1) {
    return ElMessage({
      message: $t('sys.pleaseSelectAuth'),
      type: 'warning',
      duration: 1500
    })
  }
  dataForm.menuIdList = dataForm.premType === 1 ? menuIdList : undefined
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit.value) {
        return false
      }
      if (isHtmlNull(dataForm.name)) {
        ElMessage.error($t('shopProcess.inputAllSpace'))
        return
      }
      isSubmit.value = true
      http({
        url: http.adornUrl('/platform/sysAccessKey'),
        method: dataForm.sysAccessKeyId ? 'put' : 'post',
        data: http.adornData(dataForm)
      }).then(() => {
        ElMessage({
          message: $t('remindPop.success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
            dataForm.content = ''
          }
        })
      }).catch((e) => {
        isSubmit.value = false
      })
    }
  })
}
defineExpose({ init })
</script>
